﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using ZyGames.DZPocker.Bll.Com.Share;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Common;
using ZyGames.Framework.Common.Serialization;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using ZyGames.Framework.Net;

namespace ZyGames.DZPocker.Script.CsScript.Action
{

	/// <summary>
	/// 创建角色接口
	/// </summary>
	/// <remarks>继续BaseStruct类:允许无身份认证的请求;AuthorizeAction:需要身份认证的请求</remarks>
	public class Action10005 : RegisterAction
	{
		public Action10005(HttpGet httpGet)
			: base((short)ActionType.DZCreateRole, httpGet)
		{

		}

		protected override bool GetActionParam()
		{
			return true;
		}

		protected override bool CreateUserRole(out IUser user)
		{
			user = null;
			var gameUser = GameTable.Current.GetUser(UserId);
			if (gameUser == null)
			{
				var roleFunc = new RoleFunc();
				string msg;

				if(roleFunc.VerifyRange(UserName, out msg) ||
					roleFunc.VerifyKeyword(UserName, out msg) ||
					roleFunc.IsExistNickName(UserName, out msg))
				{
					ErrorCode = Language.Instance.ErrorCode;
					ErrorInfo = msg;
					return false;
				}
				gameUser = this.CreateRole();
				roleFunc.OnCreateAfter(gameUser);

				user = new SessionUser(gameUser);
				UserLoginLog userLoginLog = new UserLoginLog();
				userLoginLog.UserId = UserId.ToString();
				userLoginLog.SessionID = Sid;
				userLoginLog.MobileType = (short)MobileType;
				userLoginLog.ScreenX = ScreenX;
				userLoginLog.ScreenY = ScreenY;
				userLoginLog.RetailId = RetailID;
				userLoginLog.AddTime = DateTime.Now;
				userLoginLog.State = (short)LoginStatus.Logined;
				userLoginLog.DeviceID = DeviceID;
				userLoginLog.Ip = GetRealIP();
				userLoginLog.Pid = gameUser.GetPassportId();
				userLoginLog.UserLv = gameUser.UserLv;
				var sender = DataSyncManager.GetDataSender();
				sender.Send(new[] { userLoginLog });
			}
			return false;
		}

		private GameUser CreateRole()
		{
			GameUser user = new GameUser(UserId);
			user.SessionID = Sid;
			user.Pid = Pid;
			user.HeadIcon = HeadID;
			user.RetailId = RetailID;
			user.NickName = UserName;
			user.RealName = "";
			user.Hobby = "";
			user.Profession = "";
			user.Sex = Sex.ToBool();
			user.UserLv = (short)ConfigEnvSet.GetInt("User.Level", 1);
			user.GiftGold = ConfigEnvSet.GetInt("User.GiftGold", 100);
			user.GameCoin = ConfigEnvSet.GetInt("User.GameCoin", 1000);
			user.VipLv = ConfigEnvSet.GetInt("User.VipLv");
			user.UserStatus = UserStatus.Normal;
			user.MsgState = true;
			user.MobileType = MobileType;
			user.ScreenX = ScreenX;
			user.ScreenY = ScreenY;
			user.ClientAppVersion = ReqAppVersion;
			user.LoginDate = DateTime.Now;
			user.CreateDate = DateTime.Now;
			user.TitleId = 1001;
			user.Property.GameId = GameID;
			user.Property.ServerId = ServerID;
			user.Birthday = new DateTime(1970, 1, 1);

			//判断Pid如果是手机号则检查手机号归属地并且设置归属地
			//判断是否是手机号
			Regex rx = new Regex(@"^[1][358][0-9]{9}$");
			if (rx.IsMatch(user.Pid))
			{
				var Url = string.Format(@"http://v.showji.com/Locating/showji.com2016234999234.aspx?m={0}&output=json&callback=querycallback&timestamp=1480066397101", user.Pid);
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
				request.Method = "GET";
				request.ContentType = "text/html;charset=UTF-8";

				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				Stream myResponseStream = response.GetResponseStream();
				StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
				string retString = myStreamReader.ReadToEnd();
				//字符串截取
				var trueValue = retString.Substring(14, retString.Length - 16);
				try
				{
					var phone = JsonUtils.Deserialize<PhoneInfo>(trueValue); 
					user.City = phone.City;
					user.CityCode = phone.AreaCode;
				}
				catch (Exception ex)
				{
					Tools.Tool.WriteErrorLine(ex.ToString());
				}
			}

			var cacheSet = new GameDataCacheSet<GameUser>();
			cacheSet.Add(user);
			cacheSet.Update();

			//增加初始背包、玩家任务表、玩家成就表
			var itemCacheSet = new GameDataCacheSet<UserItemPackage>();
			itemCacheSet.Add(new UserItemPackage(UserId));
			itemCacheSet.Update();
			var taskCacheSet = new GameDataCacheSet<UserTask>();
			taskCacheSet.Add(new UserTask(UserId));
			taskCacheSet.Update();
			var achieveCacheSet = new GameDataCacheSet<UserAchieve>();
			achieveCacheSet.Add(new UserAchieve(UserId));
			achieveCacheSet.Update();
			UserDailyRestrain restrain = new UserDailyRestrain(UserId);
			restrain.RefreshDate = DateTime.Now.AddDays(-1);
			var restrainCacheSet = new GameDataCacheSet<UserDailyRestrain>();
			restrainCacheSet.Add(restrain);
			restrainCacheSet.Update();

			return user;
		}

		//public override bool TakeAction()
		//{
		//	return true;
		//}

		//public override void BuildPacket()
		//{
		//	base.BuildPacket();
		//	//发送配置信息
		//	try
		//	{

		//		//一副牌的数据
		//		var pockerInfoList = new ShareCacheStruct<PokerInfo>().FindAll();
		//		var pockerInfo = Convert.ToBase64String(ProtoBufUtils.Serialize(pockerInfoList));
		//		this.PushIntoStack(pockerInfo);

		//		//赔率列表
		//		var outsOddsInfoList = new ShareCacheStruct<OutsOddsInfo>().FindAll();
		//		var outsOddsInfo = Convert.ToBase64String(ProtoBufUtils.Serialize(outsOddsInfoList));
		//		this.PushIntoStack(outsOddsInfo);
		//		//商店
		//		var shopInfoList = new ShareCacheStruct<ShopInfo>().FindAll();
		//		var shopInfo = Convert.ToBase64String(ProtoBufUtils.Serialize(shopInfoList));
		//		this.PushIntoStack(shopInfo);

		//	}
		//	catch (Exception ex)
		//	{
		//		Console.WriteLine(ex.Message);
		//	}
		//}
	}
}
